<template>
  <div class="attendance-records">
    <div class="page-header">
      <h2>考勤记录</h2>
    </div>
    
    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline size="default">
        <el-form-item label="姓名:">
          <el-input
            v-model="searchForm.employeeName"
            placeholder="请输入人员姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="班组名称:">
          <el-input
            v-model="searchForm.teamName"
            placeholder="请输入班组名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="日期范围:">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            start-placeholder="2025-06-26"
            end-placeholder="2025-07-25"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">确认检索</el-button>
        </el-form-item>
      </el-form>
      
      <div class="action-buttons">
        <el-button @click="handleReset">重置</el-button>
        <el-button @click="handleCalculate">重算</el-button>
        <el-button type="success" @click="handleExport">导出</el-button>
      </div>
    </div>
    
    <!-- 表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
        style="width: 100%"
        class="attendance-table"
      >
        <el-table-column prop="序号" label="序号" width="60" align="center" />
        <el-table-column prop="teamName" label="班组名称" width="120" />
        <el-table-column prop="employeeNumber" label="工号" width="100" />
        <el-table-column prop="employeeName" label="姓名" width="100" />
        <el-table-column prop="actualPunchInTime" label="上班打卡时间" width="150" />
        <el-table-column prop="punchInDevice" label="上班打卡设备" width="120" />
        <el-table-column prop="actualPunchOutTime" label="下班打卡时间" width="150" />
        <el-table-column prop="punchOutDevice" label="下班打卡设备" width="120" />
        <el-table-column prop="shiftCode" label="排班班次" width="100" />
        <el-table-column prop="attendanceStatus" label="考勤情况" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getAttendanceStatusType(row.attendanceStatus)">
              {{ getAttendanceStatusText(row.attendanceStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lateDurationHours" label="迟到时长(小时)" width="120" align="center" />
        <el-table-column prop="earlyLeaveDurationHours" label="早退时长(小时)" width="120" align="center" />
        <el-table-column prop="actualWorkHours" label="实际工作时长(小时)" width="140" align="center" />
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <span class="total-text">共{{ total }}条记录</span>
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getDailyAttendanceRecords, exportDailyAttendanceRecords } from '@/api/attendance'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

const searchForm = reactive({
  employeeName: '',
  teamName: ''
})

const dateRange = ref([
  dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
  dayjs().format('YYYY-MM-DD')
])

const pagination = reactive({
  pageNum: 1,
  pageSize: 10
})

// 监听日期范围变化
watch(dateRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    searchForm.startDate = newVal[0]
    searchForm.endDate = newVal[1]
  }
}, { immediate: true })

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      employeeName: searchForm.employeeName || undefined,
      teamName: searchForm.teamName || undefined,
      startDate: searchForm.startDate,
      endDate: searchForm.endDate
    }
    
    const res = await getDailyAttendanceRecords(params)
    const data = res.data
    
    tableData.value = data.records?.map((item, index) => ({
      ...item,
      序号: (pagination.pageNum - 1) * pagination.pageSize + index + 1,
      actualPunchInTime: item.actualPunchInTime ? 
        (item.date ? `${item.date} ${item.actualPunchInTime}` : item.actualPunchInTime) : '-',
      actualPunchOutTime: item.actualPunchOutTime ? 
        (item.date ? `${item.date} ${item.actualPunchOutTime}` : item.actualPunchOutTime) : '-',
      punchInDevice: item.punchInDevice || '-',
      punchOutDevice: item.punchOutDevice || '-',
      lateDurationHours: item.lateDurationHours || '0',
      earlyLeaveDurationHours: item.earlyLeaveDurationHours || '0',
      actualWorkHours: item.actualWorkHours || '0'
    })) || []
    
    total.value = data.total || 0
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageNum = 1
  loadData()
}

const handleReset = () => {
  searchForm.employeeName = ''
  searchForm.teamName = ''
  dateRange.value = [
    dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
    dayjs().format('YYYY-MM-DD')
  ]
  pagination.pageNum = 1
  loadData()
}

const handleCalculate = () => {
  ElMessage.info('重算功能待实现')
}

const handleExport = async () => {
  try {
    const params = {
      employeeName: searchForm.employeeName || undefined,
      teamName: searchForm.teamName || undefined,
      startDate: searchForm.startDate,
      endDate: searchForm.endDate
    }
    
    const res = await exportDailyAttendanceRecords(params)
    
    // 创建下载链接
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `考勤记录_${searchForm.startDate}_${searchForm.endDate}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
  }
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.pageNum = 1
  loadData()
}

const handleCurrentChange = (val) => {
  pagination.pageNum = val
  loadData()
}

const getAttendanceStatusType = (status) => {
  switch (status) {
    case '正常':
      return 'success'
    case '迟到':
      return 'warning'
    case '早退':
      return 'warning'
    case '缺勤':
      return 'danger'
    case '休息':
      return 'info'
    default:
      return 'info'
  }
}

const getAttendanceStatusText = (status) => {
  return status || '未知'
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.attendance-records {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      color: #333;
      margin: 0;
    }
  }
  
  .search-section {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    
    .action-buttons {
      display: flex;
      gap: 10px;
      
      .el-button {
        min-width: 80px;
      }
    }
  }
  
  .table-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
    
    .attendance-table {
      flex: 1;
    }
    
    .pagination-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ebeef5;
      
      .total-text {
        color: #666;
        font-size: 14px;
      }
    }
  }
}

// 表格样式优化
:deep(.attendance-table) {
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .el-table__row {
    &:hover {
      background-color: #f5f7fa;
    }
  }
}
</style>